package controllers

import (
	"encoding/json"
	"strconv"
	"supershare/backend/middleware"
	"supershare/backend/models"

	"github.com/beego/beego/v2/server/web"
)

// UserController 处理用户相关请求
type UserController struct {
	web.Controller
}

// LoginRequest 登录请求参数
type LoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

// LoginResponse 登录响应
type LoginResponse struct {
	Token     string        `json:"token"`
	Admin     *models.Admin `json:"admin"`
	ExpiresAt int64         `json:"expires_at"`
}

// Login 处理登录请求
func (c *UserController) Login() {
	// 解析请求参数
	var req LoginRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 验证用户名和密码
	admin, err := models.GetAdminByUsername(req.Username)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "用户名或密码错误",
		}
		c.ServeJSON()
		return
	}

	// 检查密码
	if !admin.CheckPassword(req.Password) {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "用户名或密码错误",
		}
		c.ServeJSON()
		return
	}

	// 检查账号状态
	if admin.Status != 1 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "账号已被禁用",
		}
		c.ServeJSON()
		return
	}

	// 更新登录信息
	admin.UpdateLoginInfo(c.Ctx.Input.IP())

	// 生成JWT令牌
	token, expiresAt, err := middleware.GenerateToken(admin)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "生成令牌失败",
		}
		c.ServeJSON()
		return
	}

	// 清除敏感信息
	admin.Password = ""

	// 返回登录成功响应，包含用户信息
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "登录成功",
		"data": LoginResponse{
			Token:     token,
			Admin:     admin,
			ExpiresAt: expiresAt,
		},
	}
	c.ServeJSON()
}

// GetInfo 获取当前登录用户信息
func (c *UserController) GetInfo() {
	// 从上下文中获取用户ID
	userId := c.Ctx.Input.GetData("user_id")
	if userId == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取管理员信息
	admin, err := models.GetAdminById(userId.(int64))
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取用户信息失败",
		}
		c.ServeJSON()
		return
	}
	//获取角色所有权限
	permissions := make([]*models.Permission, 0)
	if admin.FranchiseId == 0 && admin.RoleId == 0 {
		permissions, _ = models.GetAllPermissions("menu", "button")
	} else {
		permissions, _ = models.GetPermissionsByRoleId(admin.RoleId, "menu", "button")
	}

	// 返回用户信息
	c.Data["json"] = map[string]interface{}{
		"success":     true,
		"message":     "获取用户信息成功",
		"data":        admin,
		"permissions": permissions,
	}
	c.ServeJSON()
}

// UserListRequest 用户列表请求参数
type UserListRequest struct {
	Page        int    `json:"page" form:"page"`
	PageSize    int    `json:"pageSize" form:"pageSize"`
	Username    string `json:"username" form:"username"`
	RealName    string `json:"real_name" form:"real_name"`
	Status      int8   `json:"status" form:"status"`
	FranchiseId int64  `json:"franchise_id" form:"franchise_id"`
}

// UserCreateRequest 创建用户请求参数
type UserCreateRequest struct {
	Username    string `json:"username"`
	Password    string `json:"password"`
	RealName    string `json:"real_name"`
	Mobile      string `json:"mobile"`
	Email       string `json:"email"`
	Avatar      string `json:"avatar"`
	Status      int8   `json:"status"`
	FranchiseId int64  `json:"franchise_id"`
	RoleId      int64  `json:"role_id"`
}

// UserUpdateRequest 更新用户请求参数
type UserUpdateRequest struct {
	RealName    string `json:"real_name"`
	Mobile      string `json:"mobile"`
	Email       string `json:"email"`
	Avatar      string `json:"avatar"`
	Status      int8   `json:"status"`
	RoleId      int64  `json:"role_id"`
	FranchiseId int64  `json:"franchise_id"`
}

// ChangePasswordRequest 修改密码请求参数
type ChangePasswordRequest struct {
	OldPassword string `json:"oldPassword"`
	NewPassword string `json:"newPassword"`
}

// ChangePassword 修改用户密码
func (c *UserController) ChangePassword() {
	// 解析请求参数
	var req ChangePasswordRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 获取当前登录用户信息
	currentAdmin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || currentAdmin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 验证旧密码
	if !currentAdmin.CheckPassword(req.OldPassword) {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "原密码不正确",
		}
		c.ServeJSON()
		return
	}

	// 设置新密码
	err = currentAdmin.SetPassword(req.NewPassword)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "设置新密码失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 更新密码
	currentAdmin.UpdatedBy = currentAdmin.Username
	currentAdmin.BeforeUpdate()
	err = models.UpdateAdmin(currentAdmin, "Password", "UpdatedBy", "UpdatedAt")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新密码失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回成功响应
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "密码修改成功",
	}
	c.ServeJSON()
}

// List 获取用户列表
func (c *UserController) List() {
	// 获取请求参数
	page, _ := strconv.Atoi(c.GetString("page"))
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(c.GetString("pageSize"))
	if pageSize <= 0 || pageSize > 100 {
		pageSize = 10
	}

	username := c.GetString("username")
	realName := c.GetString("real_name")
	status, _ := c.GetInt8("status", -1)
	franchiseId, _ := c.GetInt64("franchise_id", -1)

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 非总管理员只能查看自己加盟商的用户
	if admin.FranchiseId != 0 {
		franchiseId = admin.FranchiseId
	}

	// 构建过滤条件
	filters := make(map[string]interface{})
	if username != "" {
		filters["username"] = username
	}
	if realName != "" {
		filters["real_name"] = realName
	}
	if status >= 0 {
		filters["status"] = int8(status)
	}
	if franchiseId > 0 {
		filters["franchise_id"] = franchiseId
	}

	// 查询用户列表
	admins, total, err := models.GetAdminList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取用户列表失败",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取用户列表成功",
		"data": map[string]interface{}{
			"list":  admins,
			"total": total,
			"page":  page,
			"size":  pageSize,
		},
	}
	c.ServeJSON()
}

// Create 创建用户
func (c *UserController) Create() {
	// 解析请求参数
	var req UserCreateRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 获取当前管理员信息
	admin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || admin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 非总管理员只能创建自己加盟商的用户
	if admin.FranchiseId != 0 {
		req.FranchiseId = admin.FranchiseId
	}

	// 检查用户名是否已存在
	existAdmin, _ := models.GetAdminByUsername(req.Username)
	if existAdmin != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "用户名已存在",
		}
		c.ServeJSON()
		return
	}

	// 创建用户
	newAdmin := &models.Admin{
		Username: req.Username,
		RealName: req.RealName,
		Mobile:   req.Mobile,
		Email:    req.Email,
		Avatar:   req.Avatar,
		Status:   req.Status,
		RoleId:   req.RoleId,
	}
	// 设置加盟商ID
	if req.FranchiseId > 0 {
		newAdmin.FranchiseId = req.FranchiseId
	}

	// 设置密码
	err = newAdmin.SetPassword(req.Password)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "设置密码失败",
		}
		c.ServeJSON()
		return
	}
	// 设置创建者信息
	newAdmin.CreatedBy = admin.Username
	// 设置更新者信息
	newAdmin.UpdatedBy = admin.Username
	newAdmin.BeforeInsert()
	// 保存用户
	id, err := models.CreateAdmin(newAdmin)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建用户失败",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建用户成功",
		"data":    id,
	}
	c.ServeJSON()
}

// Update 更新用户
func (c *UserController) Update() {
	// 获取用户ID
	id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
	if id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的用户ID",
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	var req UserUpdateRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 获取当前管理员信息
	currentAdmin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || currentAdmin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取要更新的用户信息
	admin, err := models.GetAdminById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "用户不存在",
		}
		c.ServeJSON()
		return
	}

	// 非总管理员只能更新自己加盟商的用户
	if currentAdmin.FranchiseId != 0 && admin.FranchiseId != currentAdmin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权操作其他加盟商的用户",
		}
		c.ServeJSON()
		return
	}

	// 更新用户信息
	admin.RealName = req.RealName
	admin.Mobile = req.Mobile
	admin.Email = req.Email
	admin.Avatar = req.Avatar
	admin.Status = req.Status
	admin.RoleId = req.RoleId
	if admin.FranchiseId != 0 {
		req.FranchiseId = currentAdmin.FranchiseId
	}
	admin.FranchiseId = req.FranchiseId
	// 设置更新者信息
	admin.UpdatedBy = currentAdmin.Username
	admin.BeforeUpdate()

	// 保存更新
	err = models.UpdateAdmin(admin, "RealName", "Mobile", "Email", "Avatar", "Status", "RoleId", "FranchiseId", "UpdatedBy", "UpdatedAt")
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新用户失败",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新用户成功",
	}
	c.ServeJSON()
}

// Delete 删除用户
func (c *UserController) Delete() {
	// 获取用户ID
	id, _ := strconv.ParseInt(c.Ctx.Input.Param(":id"), 10, 64)
	if id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的用户ID",
		}
		c.ServeJSON()
		return
	}

	// 获取当前管理员信息
	currentAdmin, err := middleware.GetCurrentAdmin(c.Ctx)
	if err != nil || currentAdmin == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}

	// 获取要删除的用户信息
	admin, err := models.GetAdminById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "用户不存在",
		}
		c.ServeJSON()
		return
	}

	// 非总管理员只能删除自己加盟商的用户
	if currentAdmin.FranchiseId != 0 && admin.FranchiseId != currentAdmin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权操作其他加盟商的用户",
		}
		c.ServeJSON()
		return
	}

	// 不能删除自己
	if currentAdmin.Id == id {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "不能删除当前登录的用户",
		}
		c.ServeJSON()
		return
	}

	// 删除用户
	err = models.DeleteAdmin(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "删除用户失败",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "删除用户成功",
	}
	c.ServeJSON()
}
